import axios from 'axios'; 
import { ElNotification } from 'element-plus';

const axiosInstance = axios.create({
    baseURL:"/admin",
    headers:{
        Authorization:localStorage.getItem("token")?localStorage.getItem("token"):"",
    }
});

// 添加请求拦截器
axiosInstance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axiosInstance.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    if(error.response.status === 401){
        localStorage.removeItem("token");
        window.location.href = "/login";
        // ElNotification({
        //     title:"错误提示",
        //     message:error.response.data.msg,
        //     type:"error",
        //     showClose:false,
        //     onClose:() => {
        //         window.location.href = "/login";
        //     }
        // })
    }
    return Promise.reject(error.response.data);
  });

const ApiPost = async (url,params) => {
    const response = await axiosInstance.post(url,params);
    return response.data;
}

const ApiPut = async (url,params) => {
    const response = await axiosInstance.put(url,params);
    return response.data;
}

const ApiGet = async (url,params) => {
    const response = await axiosInstance.get(url,params);
    return response.data;
}

const ApiDelete =  async (url,params) => {
    const response = await axiosInstance.delete(url,{params});
    return response.data;
}

export {
    ApiPost,
    ApiPut,
    ApiGet,
    ApiDelete
}